import { getUserInfo, getGroupInfo, getUserPermission, getCommonUserInfo } from '@/api/puma';

import router from '@/router';
import store from '@/store';
import { debug } from 'console';
import { ElMessage } from 'element-plus';

const productCode = window.XCConfig.VITE_PRODUCT_CODE || '';

export default function useLocalLogin(token: any) {
    const init = async () => {
        if (token) {
            const tokenStr = JSON.stringify(token);
            store.commit('puma/' + 'SET_TOKEN', tokenStr);

            const userInfo = await getUserInfo();
            if (userInfo) {
                const { id } = userInfo;

                // 拿权限
                try {
                    store.commit('app/setLoginLoading', true);
                    const arr = await getUserPermission({ userId: id, productCode });
                    if (arr) {
                        // selected为false的route会在执行puma/setInitData时被筛除
                        const routes = arr.map(route => {
                            const routeChildrenSelected = route.children.filter(routeChildren => {
                                return routeChildren.selected;
                            });
                            if (!routeChildrenSelected.length) {
                                route.selected = false;
                            }
                            return route;
                        });
                        await store.dispatch('puma/setRoutes', []);
                        await store.dispatch('puma/setInitData', {
                            user: userInfo,
                            token: tokenStr,
                            userPermissions: routes,
                        });
                        const pumaRoutes = store.state.puma.routes;
                        if (!pumaRoutes.length) {
                            ElMessage.error('无访问权限，请联系管理员');
                            return;
                        }
                        // 因为children.length为0的route的selected在上方代码中会被置为false，且selected为false的route会在执行puma/setInitData时被筛除，所以在这里，pumaRoutes[0].children[0]（当前登录用户有权限的第一个页面）一定存在，可直接取其path作为登录成功后的默认展示页面
                        const replacePath = pumaRoutes[0].children[0].path;
                        await router.replace(replacePath);
                        store.commit('app/setGlobalWaterMark', true);
                    }
                } catch (error) {
                    router.replace('/login');
                    ElMessage.error('登录失败');
                } finally {
                    store.commit('app/setLoginLoading', false);
                }
            }

            // 获取供应商信息
            const groupInfo = await getGroupInfo();
            if (groupInfo) {
                store.commit('userGroup/setGroupInfo', groupInfo);
            }

            // 获取潮工作身份
            const commonUserInfo = await getCommonUserInfo();
            if (commonUserInfo) {
                store.commit('userGroup/setCommonUserInfo', commonUserInfo);
            }
        }
    };
    init();
}
